package org.andromeo.connectionapi;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.andromeo.ARException;
import org.andromeo.GRSession;
import org.andromeo.Message;
import org.andromeo.MessageFactory;
import org.andromeo.User;
import org.andromeo.UserFactory;
import org.andromeo.util.ARRequester;

/**
 * Die Klasse holt die neuen Nachrichten, welche in der Seitenleiste aufpoppen.
 * 
 * @author fabian
 * 
 */
public class NewMessageListProcessor  {

	/**
	 * patterns
	 */
	public static Pattern messagelinePattern = Pattern
			.compile("<div class=\"row\".*?</div>");

	/*
	 * Matcher.group(1) is uid Matcher.group(2) is msg-id
	 */
	// id="row800178_msg32540998"
	public static final Pattern msgiduidPattern = Pattern.compile(
			"id=\"row(\\d*)_msg(\\d*)", Pattern.DOTALL);

	// title="discover20 25. Jun. - 17:56"
	// group(1) should extract username, group(2) should extract date + time
	public static final Pattern titlePattern = Pattern
			.compile("title=\"([\\S]*?)\\s(.*?)\"");
	
	
	// 25. Jun. - 17:56
	public static SimpleDateFormat sdf = new SimpleDateFormat("dd. MMM. - HH:mm",new Locale("en"));

	public static Vector<Message> getNewReceivedMessages(GRSession grsession)
			throws ARException, IOException {
		Vector<Message> newmsglist = new Vector<Message>();

		UserFactory userfab = UserFactory.getUserFactory(grsession);
		MessageFactory msgfab = MessageFactory.getMessageFactory(grsession);

		String urlstring = grsession.getGrurl();
		urlstring += grsession.getPhpSessionID();
		urlstring += "/main/personalList/PersonalListPage.php?show=msg&max=23";

		String response = ARRequester.sendRequest(grsession, urlstring, "");

		Matcher messagelineMatcher = messagelinePattern.matcher(response);

		while (messagelineMatcher.find()) {
			String messageline = messagelineMatcher.group();

			Matcher msgiduidMatcher = msgiduidPattern.matcher(messageline);
			Matcher titleMatcher = titlePattern.matcher(messageline);

			String msgidstr = null;
			String uidstr = null;
			String unamestr = null;
			String datestr = null;

			if (msgiduidMatcher.find()) {
				uidstr = msgiduidMatcher.group(1);
				msgidstr = msgiduidMatcher.group(2);
			}

			if (titleMatcher.find()) {
				unamestr = titleMatcher.group(1);
				datestr = titleMatcher.group(2);
			}

			if (msgidstr != null) {
				Message msg = msgfab.getMessageById(msgidstr);

				User user = userfab.getUserById(uidstr);
				user.setUserName(unamestr);
				msg.setMessagePartner(user);

				try {
					Date date = sdf.parse(datestr);
					msg.setMessageTimestamp(date);
				} catch (ParseException e) {
					e.printStackTrace();
					msg.setMessageTimestamp(new Date());
				}
				
				newmsglist.add(msg);
				
			}
		}

		return newmsglist;

	}
}
